[图片];
import { useRef, useState } from "react";
import type { ActionRefType } from "@alipay/techui-rule-tree";
import { RuleTree } from "@alipay/techui-rule-tree";
import type { FormInstance } from "antd";
import { Form, Input, Select, Tag } from "antd";

export default function App() {
  const [value, setValue] = useState({});
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionRefType<{ name: string }>>();

  return (
    <div>
      <p>手动设置create doms，更改样式或者设置显隐等</p>
      <p>通过onRelationChange 配合 actionRef 来达到联动的效果</p>
      <RuleTree<{ name: string }>
        formRef={formRef}
        onChange={(value) => {
          setValue(value);
        }}
        actionRef={actionRef}
        relationRender={() => {
          return (
            <Select
              options={[
                { label: "与", value: "and" },
                { label: "或", value: "or" },
                { label: "非", value: "not" },
              ]}
            />
          );
        }}
        onRelationChange={(relationValue, option, fields) => {
          console.log("relationValue", relationValue);
          console.log("fields", fields);
          // 非 - 删除多余的数据（倒着删）
          if (relationValue === "not") {
            for (let i = fields.count - 1; i > 0; i--) {
              actionRef.current!.remove(fields.levelPath, i);
            }
          }
        }}
        actionRender={(doms) => [doms.removeDom]}
        createRender={(doms, action, fields) => {
          const groupData = action.getGroupData();
          const isNot = groupData.relation === "not";
          const hasAdd =
            (fields.count < 3 && !isNot) || (isNot && fields.count < 1);
          const hasAddGroup = !isNot && fields.count < 3 && fields.deepth < 3;
          return [
            hasAdd && (
              <Tag
                key={"add"}
                style={{ cursor: "pointer" }}
                onClick={() => action.add()}
                color="blue"
              >
                添加规则
              </Tag>
            ),
            hasAddGroup && (
              <Tag
                key={"addGroup"}
                style={{ cursor: "pointer" }}
                onClick={() => action.addGroup()}
                color="orange"
              >
                添加规则组
              </Tag>
            ),
          ].filter(Boolean);
        }}
        defaultValue={{
          relation: "and",
          children: [
            {
              name: "A",
            },
            {
              name: "B",
            },
          ],
        }}
      >
        {(field) => {
          return (
            <Form.Item
              noStyle
              name={[field.name, "name"]}
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
          );
        }}
      </RuleTree>
      <pre>{JSON.stringify(value, null, 2)}</pre>
    </div>
  );
}
